// https://www.npmjs.com/package/mitt
import mitt from "mitt";

export type Events = {
  hello: {
    msg: string;
  };
  foo: number;
};

export type EvenetName = keyof Events;

const emitter = mitt<Events>();

/** 所有的事件实例 */
const eventMap = emitter.all;

/** 绑定事件 */
const addListener = <K extends EvenetName>(eventName: K, cb: (args: Events[K]) => void) => {
  const evfn = emitter.all.get(eventName);
  if (evfn && evfn.length) {
    console.log(`存在多个 ${eventName} 事件, 清空旧的事件`);
    emitter.all.set(eventName, []);
  }

  emitter.on(eventName, cb);
};

/** 删除事件 */
const removeListener = (eventName: EvenetName) => {
  emitter.off(eventName);
};

/** 发送事件 */
const emit = <K extends EvenetName>(name: K, args: Events[K]) => {
  emitter.emit(name, args);
};

export { emitter, eventMap, addListener, removeListener, emit };
